package com.zhouu.example.core.aspect;

import com.zhouu.example.core.annotation.Log;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author Zhouu
 * @date 2021-02-24 15:19
 */
@Slf4j
@Aspect
@Component
public class RequestLogAspect {

    /**
     * 配置织入点
     */
    @Pointcut("@annotation(com.zhouu.example.core.annotation.Log)")
    public void logPointCut() {

    }

    @Around("logPointCut()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        Object result = proceedingJoinPoint.proceed();
        handleLog(proceedingJoinPoint, null, request, result);
        return request;
    }

    private void handleLog(JoinPoint joinPoint, Exception e, HttpServletRequest request, Object result) {
        if (joinPoint instanceof ProceedingJoinPoint) {
            joinPoint = (ProceedingJoinPoint) joinPoint;
        }
        Log controllerLog = getAnnotationLog(joinPoint);


    }

    private Log getAnnotationLog(JoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        return method.getAnnotation(Log.class);
    }
}
